import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  InputNumber,
  message,
  Popconfirm,
  Space,
  Row,
  Col,
  Tag,
  Typography,
  Tooltip,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  StarOutlined,
  MessageOutlined,
} from "@ant-design/icons";
import {
  getComments,
  getCommentById,
  createComment,
  updateComment,
  deleteComment,
  batchDeleteComments,
} from "../api/comments";
import { useTheme } from "../contexts/ThemeContext";

const { TextArea } = Input;
const { Title, Text } = Typography;

export default function Comments() {
  const { isDarkMode } = useTheme();

  // 状态管理
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState([]);
  const [total, setTotal] = useState(0);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalLoading, setModalLoading] = useState(false);
  const [editingComment, setEditingComment] = useState(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  // 搜索参数
  const [searchParams, setSearchParams] = useState({
    page: 1,
    size: 10,
    username: "",
    articleTitle: "",
    content: "",
  });

  // 表单引用
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();

  // 获取评论列表
  const fetchComments = async (params = searchParams) => {
    setLoading(true);
    try {
      const response = await getComments(params);
      // requestWithErrorHandling 已经处理了错误，这里直接使用数据
      setTableData(response.data.list || []);
      setTotal(response.data.total || 0);
    } catch (error) {
      console.error("获取评论列表失败:", error);
      message.error(error.message || "获取评论列表失败");
    } finally {
      setLoading(false);
    }
  };

  // 初始加载
  useEffect(() => {
    fetchComments();
  }, []);

  // 搜索处理
  const handleSearch = (values) => {
    const newParams = {
      ...searchParams,
      page: 1,
      username: values.username || "",
      articleTitle: values.articleTitle || "",
      content: values.content || "",
    };
    setSearchParams(newParams);
    fetchComments(newParams);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    const newParams = {
      page: 1,
      size: 10,
      username: "",
      articleTitle: "",
      content: "",
    };
    setSearchParams(newParams);
    fetchComments(newParams);
  };

  // 分页处理
  const handleTableChange = (pagination) => {
    const newParams = {
      ...searchParams,
      page: pagination.current,
      size: pagination.pageSize,
    };
    setSearchParams(newParams);
    fetchComments(newParams);
  };

  // 新增评论
  const handleAdd = () => {
    setEditingComment(null);
    setModalVisible(true);
    form.resetFields();
  };

  // 编辑评论
  const handleEdit = async (record) => {
    try {
      const response = await getCommentById(record.id);
      // requestWithErrorHandling 已经处理了错误
      setEditingComment(response.data);
      setModalVisible(true);
      form.setFieldsValue({
        content: response.data.content,
        star: response.data.star,
        articleTitle: response.data.articleTitle,
        username: response.data.username,
      });
    } catch (error) {
      console.error("获取评论详情失败:", error);
      message.error(error.message || "获取评论详情失败");
    }
  };

  // 删除评论
  const handleDelete = async (id) => {
    try {
      await deleteComment(id);
      // requestWithErrorHandling 已经处理了错误
      message.success("删除成功");
      fetchComments();
      setSelectedRowKeys([]);
    } catch (error) {
      console.error("删除评论失败:", error);
      message.error(error.message || "删除失败");
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请选择要删除的评论");
      return;
    }

    try {
      await batchDeleteComments(selectedRowKeys);
      // requestWithErrorHandling 已经处理了错误
      message.success("批量删除成功");
      fetchComments();
      setSelectedRowKeys([]);
    } catch (error) {
      console.error("批量删除失败:", error);
      message.error(error.message || "批量删除失败");
    }
  };

  // 提交表单
  const handleSubmit = async (values) => {
    setModalLoading(true);
    try {
      if (editingComment) {
        // 编辑
        await updateComment({
          id: editingComment.id,
          ...values,
        });
      } else {
        // 新增
        await createComment(values);
      }

      // requestWithErrorHandling 已经处理了错误
      message.success(editingComment ? "修改成功" : "添加成功");
      setModalVisible(false);
      fetchComments();
    } catch (error) {
      console.error("提交失败:", error);
      message.error(error.message || "操作失败");
    } finally {
      setModalLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: 80,
      sorter: (a, b) => a.id - b.id,
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
      width: 120,
      render: (text) => <Tag color="blue">{text}</Tag>,
    },
    {
      title: "文章标题",
      dataIndex: "articleTitle",
      key: "articleTitle",
      width: 150,
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip title={text}>
          <Tag color="green">{text}</Tag>
        </Tooltip>
      ),
    },
    {
      title: "评论内容",
      dataIndex: "content",
      key: "content",
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip title={text} overlayStyle={{ maxWidth: "500px" }}>
          <div
            style={{
              cursor: "pointer",
              whiteSpace: "nowrap",
              overflow: "hidden",
              textOverflow: "ellipsis",
            }}>
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: "评分",
      dataIndex: "star",
      key: "star",
      width: 100,
      render: (star) => (
        <Space>
          <StarOutlined style={{ color: "#faad14" }} />
          <span>{typeof star === "number" ? star.toFixed(1) : star}</span>
        </Space>
      ),
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      width: 180,
      render: (time) => (time ? new Date(time).toLocaleString() : "-"),
    },
    {
      title: "更新时间",
      dataIndex: "updateTime",
      key: "updateTime",
      width: 180,
      render: (time) => (time ? new Date(time).toLocaleString() : "-"),
    },
    {
      title: "操作",
      key: "action",
      width: 160,
      fixed: "right",
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确认删除"
            description="确定要删除这条评论吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消">
            <Button type="link" size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
    ],
  };

  return (
    <div style={{ maxWidth: 1200, margin: "20px auto", padding: "0 16px" }}>
      {/* 页面标题 */}
      <div style={{ textAlign: "center", marginBottom: 32 }}>
        <Title level={2} style={{ color: "#1890ff", marginBottom: 8 }}>
          <MessageOutlined /> 评论管理
        </Title>
        <Text type="secondary" style={{ fontSize: 16 }}>
          基于 Spring Boot 服务的评论管理
        </Text>
      </div>

      <Card
        style={{
          borderRadius: 12,
          boxShadow: isDarkMode
            ? "0 2px 12px rgba(0,0,0,0.3)"
            : "0 2px 12px #eee",
          backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
          borderColor: isDarkMode ? "#434343" : "#d9d9d9",
          transition: "all 0.3s ease",
        }}>
        {/* 搜索区域 - 单独的Card */}
        <Card
          size="small"
          title={
            <Space>
              <SearchOutlined />
              <span>搜索条件</span>
            </Space>
          }
          style={{
            marginBottom: 24,
            backgroundColor: isDarkMode ? "#262626" : "#fafafa",
            borderColor: isDarkMode ? "#434343" : "#d9d9d9",
          }}>
          <Form form={searchForm} onFinish={handleSearch} layout="inline">
            {/* 第一行：关键词搜索（占满一行） */}
            <Row gutter={[12, 12]} style={{ width: "100%" }}>
              <Col xs={24}>
                <Form.Item
                  name="content"
                  style={{ marginBottom: 0, width: "100%" }}>
                  <Input
                    placeholder="搜索评论内容"
                    allowClear
                    prefix={<SearchOutlined />}
                  />
                </Form.Item>
              </Col>
            </Row>

            {/* 第二行：其他条件 */}
            <Row gutter={[12, 12]} style={{ marginTop: 12, width: "100%" }}>
              <Col xs={24} sm={12} md={8}>
                <Form.Item
                  name="username"
                  style={{ marginBottom: 0, width: "100%" }}>
                  <Input placeholder="输入用户名" allowClear />
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={8}>
                <Form.Item
                  name="articleTitle"
                  style={{ marginBottom: 0, width: "100%" }}>
                  <Input placeholder="输入文章标题" allowClear />
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={8}>
                <Form.Item style={{ marginBottom: 0, width: "100%" }}>
                  <Space style={{ width: "100%" }}>
                    <Button
                      type="primary"
                      icon={<SearchOutlined />}
                      htmlType="submit">
                      搜索
                    </Button>
                    <Button icon={<ReloadOutlined />} onClick={handleReset}>
                      重置
                    </Button>
                  </Space>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Card>

        {/* 操作按钮 */}
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增评论
            </Button>
            <Popconfirm
              title="确认批量删除"
              description={`确定要删除选中的 ${selectedRowKeys.length} 条评论吗？`}
              onConfirm={handleBatchDelete}
              okText="确定"
              cancelText="取消"
              disabled={selectedRowKeys.length === 0}>
              <Button
                danger
                icon={<DeleteOutlined />}
                disabled={selectedRowKeys.length === 0}>
                批量删除 ({selectedRowKeys.length})
              </Button>
            </Popconfirm>
            <Button icon={<ReloadOutlined />} onClick={() => fetchComments()}>
              刷新
            </Button>
          </Space>
        </div>

        {/* 表格 */}
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={tableData}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            current: searchParams.page,
            pageSize: searchParams.size,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            pageSizeOptions: ["10", "20", "50", "100"],
          }}
          onChange={handleTableChange}
        />
      </Card>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={editingComment ? "编辑评论" : "新增评论"}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
        destroyOnHidden>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            star: 5,
          }}>
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: "请输入用户名" },
              { max: 50, message: "用户名不能超过50个字符" },
            ]}>
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            name="articleTitle"
            label="文章标题"
            rules={[
              { required: true, message: "请输入文章标题" },
              { max: 200, message: "文章标题不能超过200个字符" },
            ]}>
            <Input placeholder="请输入文章标题" />
          </Form.Item>

          <Form.Item
            name="content"
            label="评论内容"
            rules={[
              { required: true, message: "请输入评论内容" },
              { max: 1000, message: "评论内容不能超过1000个字符" },
            ]}>
            <TextArea
              placeholder="请输入评论内容"
              rows={4}
              showCount
              maxLength={1000}
            />
          </Form.Item>

          <Form.Item
            name="star"
            label="评分"
            rules={[
              { required: true, message: "请输入评分" },
              {
                type: "number",
                min: 0,
                max: 10,
                message: "评分必须在0-10之间",
              },
            ]}>
            <InputNumber
              min={0}
              max={10}
              step={0.1}
              precision={1}
              placeholder="请输入评分(0-10)"
              style={{ width: "100%" }}
            />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: "right" }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>取消</Button>
              <Button type="primary" htmlType="submit" loading={modalLoading}>
                {editingComment ? "保存" : "创建"}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
